import os, sys

import pygame
from pygame.locals import *

if not pygame.font: print 'Warning: fonts module did not load'
if not pygame.mixer: print 'Warning: mixer module did not load'

def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image#, image.get_rect()

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer:
        return NoneSound()
    fullname = os.path.join('data', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error, message:
        print 'Cannot load sound:', wav
        raise SystemExit, message
    return sound

class AnimatedImage(object):
    def __init__(self, images, frame_rate=7.7, frame_idx=0):
        self.frames = []
        self.frame_rate = frame_rate
        self.frame_idx = frame_idx
        self.last_frame_time = pygame.time.get_ticks()

    def update(self):
        elapsed = pygame.time.get_ticks() - self.last_frame_time
        if elapsed >= 1000.0 / self.frame_rate:
            self.frame_idx += 1
            if self.frame_idx == len(self.frames):
                self.frame_idx = 0
            self.last_frame_time = pygame.time.get_ticks()
        return self.getImage()
        
    def getImage(self):
        return self.frames[self.frame_idx].copy()
